package com.gas.gm.util.converter.xml;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import com.gas.gm.model.Account;
import com.gas.gm.model.Token;

public class AccountXMLParser extends GasXMLParser<Account> {
	
	private Account account;
	
	private String value;
	
	private List<Account> accounts;
	
	public AccountXMLParser() {
		this.accounts=new ArrayList<Account>();
	}
	
	

	@Override
	public void parseDocument(String filename) {
		SAXParserFactory factory=SAXParserFactory.newInstance();
		try {
			SAXParser saxParser=factory.newSAXParser();
			saxParser.parse(filename,this);
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public Account getObject(String key) {
		account=new Account();
		Iterator<Account> iter=accounts.iterator();
		while(iter.hasNext()){
			Account found=iter.next();
			if(key.equals(found.getSystemId())){
				account=found;
				break;
			}else{
				account=null;
			}
		}
		return account;
		
	}

	@Override
	public Collection<Account> getObjects() {
		return accounts;
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		value=new String(ch,start,length);
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if(qName.equalsIgnoreCase("account")){
			accounts.add(account);
		}else if(qName.equalsIgnoreCase("systemId")){
			account.setSystemId(value);
		}else if(qName.equalsIgnoreCase("password")){
			account.setPassword(value);
		}else if(qName.equalsIgnoreCase("companyNumber")){
			account.setCompanyNumber(value);
		}else if(qName.equalsIgnoreCase("token")){
			account.setToken(new Token(Integer.parseInt(value)));
		}
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		value="";
		if(qName.equalsIgnoreCase("account")){
			this.account=new Account();
		}
	}

	@Override
	public void printData() {
		Iterator<Account> iter=accounts.iterator();
		while(iter.hasNext()){
			System.out.println(iter.next().toString());
		}
	}
	
	

}
